# Untitled - By: 64386 - Sun May 12 2024

# Untitled - By: 64386 - Sun Apr 21 2024

import sensor, image, time, math
import binascii
from pyb import UART
from struct import *

sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QQVGA)
sensor.skip_frames(time = 2000)
uart = UART(3, 115200, timeout_char=1000)   #串口定义
clock = time.clock()
red = (32, 57, 25, 127, 23, 127)  #红色色值
d0 = []
d1 = []
d2 = []
d3 = []
d0_x = []
d0_y = []
d1_x = []
d1_y = []
d2_x = []
d2_y = []
d3_x = []
d3_y = []
flag_zuobiao = 0
flag_red = 0
flag_uart = 0
code = []
blob = []
while(True):
    clock.tick()
    img = sensor.snapshot()
    #畸变矫正
    img = sensor.snapshot().lens_corr(strength = 1.5, zoom = 1.0)
#串口接收
    flag = uart.any()

    if flag>0:
        rec_data = uart.read()                    #接收来自esp32的指令
        val_rec = x = int.from_bytes(rec_data,'big')   #解码指令
        if val_rec == 1:
            print("ok")

#寻找红色色块
    blobs = img.find_blobs([red])
    time.sleep_ms(1000)
    while flag_red < 1:
        for blob in blobs:
            img.draw_cross(blob[5],blob[6])   #色块画十字
            img.draw_rectangle(blob.rect())   #框住色块
            print(blob[5], blob[6])
        flag_red = flag_red + 1
#锚定黑色方框
    for r in img.find_rects(threshold = 10000):

        for p in r.corners(): img.draw_circle(p[0], p[1], 5, color = (0, 0, 255))  #在四个角上画圆圈标记
        #print(r)
        #print(r.corners())
        i = r.corners()
        while flag_zuobiao < 1:
            d0.append(i[0])
            d1.append(i[1])
            d2.append(i[2])
            d3.append(i[3])
            d0_x = d0[0][0]
            d0_y = d0[0][1]
            d1_x = d1[0][0]
            d1_y = d1[0][1]
            d2_x = d2[0][0]
            d2_y = d2[0][1]
            d3_x = d3[0][0]
            d3_y = d3[0][1]
            print(d0)
            print(d1)
            print(d2)
            print(d3)
            print(d1_x)

            flag_zuobiao = flag_zuobiao + 1
        #time.sleep(1)



#串口发送
    code = [blob[5],blob[6],d0_x,d0_y,d1_x,d1_y,d2_x,d2_y,d3_x,d3_y]  #int 数组
    print(code)
    val = bytes(code)   #byte数据
    print(val)
    mun = list(val)     #测试byte解码
    print(mun)
    flag_uart = flag_uart + 1
#串口接收


    uart.write(val)     #串口发送
    time.sleep_ms(1000)

